var app = getApp();
import {
  getCitiesList,
  majorPageList,
  citySubjectList,
  addScore
} from '../../api/api';;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    citys: {}, //获取到的所有城市
    letter: [], //获取到的所有字母
    searchCity: 0,
    toView: '', //点击跳转的id
    scrollTop: '',
    citysHeight: [], //所有字母大模块的top
    azHeight: 0, //每个字母平均的高度
    azTop: 0,
    index: '',
    activeAZ: 'A1',
    touchFlag: false,
    userCities: [],
    city: '选择您所在的城市',
    bottomLift: getApp().globalData.bottomLift,
    type: '',
    pageNo: 1,
    pageSize: 20,
    categoty: 'major'
  },

  onLoad: function (options) {
    if (options.type) {
      this.setData({
        type: options.type
      })
    }
    if (options.category) {
      const category = options.category
      this.setData({
        category
      })
      category == 'city' ? this.fetch() : this.getMajorList()
    }
    this.setData({
      disabled: wx.getStorageSync('subjectInfo') ? true : false
    })
  },

  onShow() {
    this.setData({
      city: wx.getStorageSync('userCitys').name
    })
  },
  confrimCity() {
    wx.switchTab({
      url: '/pages/findHome/index',
    })
  },

  selectCity(evt) {
    var {
      index,
      child
    } = evt.currentTarget.dataset;
    const {
      list,
      type,
      disabled
    } = this.data
    var page = getCurrentPages()
    var prepage = page[page.length - 2]
    if (type === 'index') {
      if (child.code !== wx.getStorageSync('userCitys').code) {
        if (!disabled) {
          wx.showModal({
            confirmColor: '#fca400',
            title: '提示',
            content: '省份一经选择，则无法修改，是否确定选择' + child.name + '?',
            success: function (res) {
              if (res.confirm) {
                wx.removeStorageSync('mainSubject')
                wx.removeStorageSync('chooseList')
                wx.removeStorageSync('ids')
                child['lock'] = false
                wx.setStorageSync('userCitys', child)
                prepage.setData({
                  showModal: true,
                  showFilterModal: false,
                  currentRegion: child
                })
                // this.updateScore()
                wx.navigateBack()
              } else {
                wx.navigateBack()
              }
            }
          })
        } else {
          wx.showModal({
            confirmColor: '#fca400',
            title: '提示',
            content: '您当前已选择省份：' + wx.getStorageSync('userCitys').name + ',无法修改其他省份。如需修改,请联系客服',
          })
        }
      } else {
        wx.navigateBack()
      }
      return
    }
    if (type == 'volunteer') {
      prepage.setData({
        currentRegion: child
      })
      wx.navigateBack({
        delta: 1,
      })
      return
    }
    if (prepage) {
      //prepage=='/pages/index/index 触发两次getCitySubject()方法'
      prepage.setData({
        currentRegion: child
      })
      prepage.onLoad()
      wx.navigateBack({
        delta: 1,
      })
    } else {
      wx.switchTab({
        url: '/pages/index/index',
      });
    }
  },
  async updateScore() {
    const code = wx.getStorageSync('userCitys').code
    const name = wx.getStorageSync('userCitys').name
    const params = {
      firstSelect: '',
      secondSelect: '',
      provinceId: code,
      province: name
    }

    const {
      message
    } = await addScore(params)
    if (message) {
      wx.navigateBack()
    }
  },
  selectMajor(e) {
    const {
      code,
      name
    } = e.currentTarget.dataset.child
    var majors = {
      code: code,
      name: name
    }
    wx.setStorageSync('majors', majors)
    var page = getCurrentPages()
    var prepage = page[page.length - 2]

    if (prepage) {
      prepage.setData({
        majors: majors
      })
      prepage.onLoad()
      wx.navigateBack({
        delta: 1,
      })
    }
    // wx.navigateBack({ })
  },
  async getMajorList() {
    const {
      pageNo,
      pageSize
    } = this.data

    const params = {
      level: 3,
      pageNo,
      pageSize
    }
    const {
      result
    } = await majorPageList(params)

    if (result.records.length == 0) {
      return
    }
    this.setData({
      ['list[' + (pageNo - 1) + ']']: result.records,
      pageNo: pageNo + 1,
    })
  },
  async getCitySubject() {
    // console.log('city--getCitySubject', )
    const code = wx.getStorageSync('userCitys').code
    const {
      result
    } = await citySubjectList(code)
    //首选科目
    const mainList = result.filter(function (item, index, arr0) {
      return item.isPreferred > 0
    })
    const subjectList = result.filter(function (item, index, arr0) {
      return item.isPreferred == 0
    })
    this.setData({
      list1: mainList
    })
    const mainSubject = mainList.length > 0 ? mainList[0].subjectsId : ''
    const chooseList = mainList.length > 0 ? [mainList[0]].concat(subjectList.splice(0, 2)) : subjectList.splice(0, 3)
    const ids = chooseList.map((item) => {
      return item.subjectsId
    })
    wx.setStorageSync('ids', ids.splice(0, 3))
    wx.setStorageSync('chooseList', chooseList)
    wx.setStorageSync('mainSubject', mainSubject)
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async fetch() {
    const params = {
      level: 'L1'
    }
    const {
      type
    } = this.data
    const {
      result
    } = await getCitiesList(params);
    const list = [{
      children: [],
      code: 0,
      id: 0,
      name: "全国",
      parentCode: 0
    }]
    if (result.length == 0) {
      return
    }
    this.setData({
      ['list[0]']: type === 'school' ? list.concat(result) : result
    })
    this.setData({
      userCities: type === 'school' ? list.concat(result) : result
    })

  },
  onReachBottom() {
    const {
      pageSize,
      list,
      category
    } = this.data
    if (category == 'city') return
    const count = list.length - 1
    // console.log(count)
    if (list[count].length < pageSize) return
    this.getMajorList()
  },
})